<?php
header('HTTP/1.1 200 OK');
error_reporting(0);
define('DIR', dirname(__FILE__));
/** ======================================================================================================= */

// 工作模式 
$logicroot = "yunhe"; // 如果不为空,则是子目录模式

// 设置模板
$template = "default"; // 模板名称

// 标题前缀
$title_prefix = "2"; //1 为开启 2为关闭

//文章加括号
$kuo_jia = "2"; //1 为开启 2为关闭
$kuo_shu = 2;
$kuo_fu = '】【';

//文章加ascii码
$ascii_jia = "2"; //1 为开启 2为关闭

//缓存开关
$cache = "2"; //1 为开启 2为关闭
$page_cache_time = 9999999;  //缓存时间

/** ======================================================================================================= */
// 生成指定长度的随机字符串
function randKey($length)
{
    $chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890';
    $key = '';
    for ($i = 0; $i < $length; $i++) {   
         $key .= $chars[random_int(0, strlen($chars) - 1)];
     }   
     return $key;   
}

// 随机获取数组中的一个元素
function varray_rand($arr)
{
    $keys = array_keys($arr);
    return $arr[$keys[array_rand($keys)]];
}

// 读取目录下文件和子目录名称
function get_folder_files($folder)
{
    if (!is_string($folder) || !is_dir($folder)) {
        return [];
    }
    $files = scandir($folder);
    if ($files === false) {
        return [];
    }
    $ignoreFiles = ['.', '..', '.gitkeep', '.htaccess', '.DS_Store', 'Thumbs.db'];
    return array_values(array_filter($files, function($file) use ($ignoreFiles) {
        return !in_array($file, $ignoreFiles);
    }));
}

// 按指定长度切割并添加分隔符
function cut_string($str, $cut_length, $f)
{
    if (!is_string($str) || $cut_length <= 0) {
        return '';
    }
    $len = mb_strlen($str, 'utf-8');
    $content = '';
    $special_chars = '“”’‘；：、|、？。》，《【】）（！~·';
    for ($i = 0; $i < $len; $i += $cut_length) {
        $qzw = mb_substr($str, $i, $cut_length, 'utf-8');
        // 判断是否为汉字（UTF-8编码范围），并且不在特殊字符列表中
        if (preg_match('//u', $qzw) && mb_strlen($qzw, 'utf-8') === 1 && strpos($special_chars, $qzw) === false) {
            // 若为单个汉字且不在特殊字符中，则拼接分隔符
            $qzw .= $f;
        }
        $content .= $qzw;
    }
    return trim($content);
}

/** ======================================================================================================= */

// 随机句子
$wenku_list = get_folder_files(DIR . '/data/juzi/');
$wenku2_list = get_folder_files(DIR . '/data/juzi2/');
$juzi = file(DIR . '/data/juzi/' . varray_rand($wenku_list));
$juzi2 = file(DIR . '/data/juzi2/' . varray_rand($wenku2_list));

// 随机关键词
$key_list = get_folder_files(DIR . '/data/keywords/');
$kygjcs = file(DIR . '/data/keywords/' . varray_rand($key_list));

// 随机图片
$image_list = get_folder_files(DIR . '/data/images/');

// 绑定模板
$domain = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'] . ($logicroot ? '/' . trim($logicroot, '/') : '');
$requestPath = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
// 如果 $logicroot 非空，则表示当前站点是以该子目录为根目录
if (!empty($logicroot)) {
    $logicroot = '/' . trim($logicroot, '/');
    if (strpos($requestPath, $logicroot) !== 0) {
        $requestPath = $logicroot . $requestPath;
    }
    $requestPath = substr($requestPath, strlen($logicroot));
}
// 如果为空路径，默认指向 index.html
$uri = trim(($requestPath === '' ? '/index.html' : $requestPath), '/'); 
if (preg_match('/\.(css|js|jpg|jpeg|png|gif|svg|webp|ico|doc|docx|xls|xlsx|ppt|pptx|pdf|psd)$/', $uri)) {
    readfile($_SERVER['DOCUMENT_ROOT'] . '/' . $uri);
    exit;
} else if (str_ends_with($uri, 'robots.txt')) {
    header("Content-Type: text/plain");
    $robots = "User-agent: *" . PHP_EOL;
    $robots .= "Disallow: /data/" . PHP_EOL;
    $robots .= "Sitemap: " . $domain . "/sitemap.xml";
    echo $robots;
    exit;
} else if (str_ends_with($uri, 'sitemap.xml') || str_ends_with($uri, 'sitemap.txt')) {
    $directories = array('news', 'blog', 'page', 'post', 'article');
    $map = '';
    if (str_ends_with($uri, 'sitemap.xml')) {
        header("Content-Type: text/xml");
        $date = date("Y-m-d");
        $map .= '<?xml version="1.0" encoding="UTF-8"?>' . PHP_EOL;
        $map .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9" xmlns:mobile="http://www.baidu.com/schemas/sitemap-mobile/1/">' . PHP_EOL;
        for ($i = 0; $i < 2000; $i++) {
            $tmp = $domain . '/' . $directories[array_rand($directories)] . '/' . randKey(16) . '.html';
            $map .= "\t<url>" . PHP_EOL;
            $map .= "\t\t<loc>{$tmp}</loc>" .PHP_EOL;
            $map .= "\t\t<mobile:mobile type=\"pc,mobile\"/>" .PHP_EOL;
            $map .= "\t\t<lastmod>{$date}</lastmod>" . PHP_EOL;
            $map .= "\t\t<changefreq>daily</changefreq>" . PHP_EOL;
            $map .= "\t\t<priority>0.6</priority>" . PHP_EOL;
            $map .= "\t</url>" . PHP_EOL;
        }
        $map .= '</urlset>';
    }else{
        header("Content-Type: text/plain");
        for ($i = 0; $i < 2000; $i++) {
            $map .= $domain . '/' . $directories[array_rand($directories)] . '/' . randKey(16) . '.html' . "\n";
        }
    }
    echo rtrim($map, "\n"); exit;
} else if ($uri === 'about.html') {
    $temp = 'about.html';
} else if ($uri === 'contact.html') {
    $temp = 'contact.html';
} else if ($uri === '' || $uri === 'index.html') {
    $temp = 'index.html';
} else {
    $parts = explode('/', $uri);
    $last_part = end($parts);
    $ext = pathinfo($uri, PATHINFO_EXTENSION);
    if ($ext === 'html' && $last_part !== 'index.html') {
        $temp = 'article.html';
    } else {
        if ($ext !== 'html' || $last_part === 'index.html') {
            $temp = 'list.html';
        } else {
            $temp = 'contact.html';
        }
    }
}
$moban = file_get_contents(DIR . '/themes/'.$template. '/' . $temp);

/** ======================================================================================================= */

$prefixs = file(DIR . '/data/prefix.txt'); // 标题前缀
$titlemxs = file(DIR . '/data/title.txt'); // 页面标题
$descriptions = file(DIR . '/data/description.txt'); // 页面描述
$links = file(DIR . '/data/link.txt'); // 外链
$guanggs = file(DIR . '/data/ads.txt'); // 广告
$mingzs = file(DIR . '/data/name.txt'); // 名字
$gsms = file(DIR . '/data/company.txt'); // 公司名
$quyus = file(DIR . '/data/quyu.txt'); // 地区
$laiyuans = file(DIR . '/data/laiyuan.txt'); // 来源
$ascii_sz = file(DIR . '/data/ascii.txt'); // ascii码


$moban = str_replace('<云核_标题>', trim(varray_rand($titlemxs)), $moban);
if ($title_prefix == '1') { $moban = str_replace('<云核_前缀>', trim(varray_rand($prefixs)), $moban); }
$moban = str_replace('<云核_描述>', trim(varray_rand($descriptions)), $moban);

$link = count(explode('<云核_外链>', $moban)) - 1;
for ($lk = 0; $lk < $link; $lk++) {
    $moban = preg_replace('/<云核_外链>/', trim(varray_rand($links)), $moban, 1);
}

$moban = str_replace('<云核_广告>', trim(varray_rand($guanggs)), $moban);

$mingz = count(explode('<云核_名字>', $moban)) - 1;
for ($mz = 0; $mz < $mingz; $mz++) {
    $moban = preg_replace('/<云核_名字>/', trim(varray_rand($mingzs)), $moban, 1);
}

$moban = str_replace('<云核_公司名>', trim(varray_rand($gsms)), $moban);

$moban = str_replace('<云核_来源>', trim(varray_rand($laiyuans)), $moban);

$moban = str_replace('<云核_地区>', trim(varray_rand($quyus)), $moban);

$wzmk = '';
for ($i = 0; $i < mt_rand(8,15); $i++) { $wzmk.="<p><云核_句子></p>\r\n"; }

$moban = str_replace('<云核_文章模块>', $wzmk, $moban);

$kygjc = count(explode('<云核_随机关键词>', $moban)) - 1;
for ($ksp = 0; $ksp < $kygjc; $ksp++) {
    $moban = preg_replace('/<云核_随机关键词>/', trim(varray_rand($kygjcs)), $moban, 1);
}
$moban = str_replace('<云核_关键词1>', trim(varray_rand($kygjcs)), $moban);
$moban = str_replace('<云核_关键词2>', trim(varray_rand($kygjcs)), $moban);
$moban = str_replace('<云核_关键词3>', trim(varray_rand($kygjcs)), $moban);
$moban = str_replace('<云核_关键词4>', trim(varray_rand($kygjcs)), $moban);
$moban = str_replace('<云核_关键词5>', trim(varray_rand($kygjcs)), $moban);
$moban = str_replace('<云核_关键词6>', trim(varray_rand($kygjcs)), $moban);

$wk = count(explode('<云核_句子>', $moban)) - 1;
for ($wi = 0; $wi < $wk; $wi++) {
    $gdjuzi= trim(varray_rand($juzi));
    if($kuo_jia == "1"){
        $gdjuzi= cut_string($gdjuzi,3,'】【');
    }
    
    if($ascii_jia == "1"){
        $gdjuzi= cut_string($gdjuzi,mt_rand(5,15),'<云核_随机字符><云核_ascii><云核_随机字符>');
    }
    $moban = preg_replace('/<云核_句子>/',$gdjuzi, $moban, 1);
    $moban = preg_replace('/<云核_句子a>/',$gdjuzi, $moban, 1);
    $moban = preg_replace('/<云核_句子b>/',$gdjuzi, $moban, 1);
    $moban = preg_replace('/<云核_句子c>/',$gdjuzi, $moban, 1);  
}

$wk = count(explode('<云核_句子2>', $moban)) - 1;
for ($wi = 0; $wi < $wk; $wi++) {
    $gdjuzi2= trim(varray_rand($juzi2));
    $moban = preg_replace('/<云核_句子2>/',$gdjuzi2, $moban, 1);
    $moban = preg_replace('/<云核_句子2a>/',$gdjuzi2, $moban, 1);
    $moban = preg_replace('/<云核_句子2b>/',$gdjuzi2, $moban, 1);
    $moban = preg_replace('/<云核_句子2c>/',$gdjuzi2, $moban, 1);
        
}

$asciiz = count(explode('<云核_ascii>', $moban)) - 1;
for ($sp = 0; $sp < $asciiz; $sp++) {
    $moban = preg_replace('/<云核_ascii>/', trim(varray_rand($ascii_sz)), $moban, 1);
}

$tupian = count(explode('<云核_随机图片>', $moban)) - 1;
for ($tui = 0; $tui < $tupian; $tui++) {
    if (empty($image_list)) {
        $images = file(DIR . '/data/images.txt'); // 图片
        $moban = preg_replace('/<云核_随机图片>/', trim(varray_rand($images)), $moban, 1);
    } else {
        $moban = preg_replace('/<云核_随机图片>/', $domain.'/images/' . varray_rand($image_list), $moban, 1);
    }
}

for ($i=0; $i < 40 ; $i++) { 
    $moban=preg_replace('/<云核_随机时钟>/', date('Y-m-d H:i:s',time()-$i*360), $moban,1);
}
$moban = str_replace('<云核_时钟>', date('G:i:s'), $moban);
$moban = str_replace('<云核_年>', date('Y'), $moban);
$moban = str_replace('<云核_月>', date('m'), $moban);
$moban = str_replace('<云核_日>', date('d'), $moban);
$moban = str_replace('<云核_发布时间>', date('Y-m-d'), $moban);
$sj5 = count(explode('<云核_随机时间>', $moban)) - 1;
for ($i = 0; $i < $sj5; $i++) {
    $moban = preg_replace('/<云核_随机时间>/',date('Y-m-d', strtotime('-'.mt_rand(1, 90).' day')), $moban, 1);
}

$zf1 = count(explode('<云核_随机字符>', $moban)) - 1;
for ($ii = 0; $ii < $zf1; $ii++) {
    $moban = preg_replace('/<云核_随机字符>/', randKey(2), $moban, 1);
}
$ri5 = count(explode('<云核_随机数字>', $moban)) - 1;
for ($i = 0; $i < $ri5; $i++) {
    $moban = preg_replace('/<云核_随机数字>/', mt_rand(1, 9999), $moban, 1);
}

/** ======================================================================================================= */
$moban = str_replace('<云核_当前域名>', $domain . ($logicroot ? '/' . trim($logicroot, '/') : ''), $moban);
$moban = str_replace('<云核_当前链接>', $_SERVER['REQUEST_URI'], $moban);


// 不启用缓存
$isbot = preg_match('/\b(Baiduspider|Sogou\s+Spider|Sogou\s+web\s+spider|360Spider|Bytespider|YisouSpider|bingbot|Googlebot|Yahoo!\s+Slurp|YandexBot|DuckDuckGo)\b/i', $_SERVER['HTTP_USER_AGENT']);
if (($cache == "2") || ($cache == "1" && !$isbot)) {echo $moban; exit; } 

// 获取目录名
$jq_mulu = dirname($requestPath);
// 处理文件名
$jq_yemian = basename($requestPath);

// 支持伪静态：将 /about 映射为 /about.html
if ($jq_yemian === '' || pathinfo($jq_yemian, PATHINFO_EXTENSION) === '') {
    $jq_yemian = '/' . $jq_yemian . '.html';
} else {
    $jq_yemian = '/' . $jq_yemian;
}

// 构建缓存路径
$url_mulu = "cache/" . $yuming . $jq_mulu;
$url_page = $url_mulu . $jq_yemian;
// 创建缓存目录并写入内容
if (!is_dir($url_mulu)) {
    mkdir($url_mulu, 0777, true);
    file_put_contents($url_page, $moban);
} else {
    if ((time() - filemtime($url_page)) > $page_cache_time) {
        file_put_contents($url_page, $moban);
    }
}

// 输出缓存文件
echo file_get_contents($url_page);
?>